<template>
  <div>
    <el-form :inline="false" class="m-form" ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item class="m-form-item" label="审批流程" prop="processId">
        <el-select v-model="form.processId" placeholder="请选择" @change="handleChange">
          <el-option
            v-for="item in processList"
            :key="item.id"
            :label="item.displayName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <FormIndex :ref="instanceUrl" :form-key="instanceUrl" />
  </div>
</template>
<script>
import { list as listProcess } from '@/api/wf/wf.process.service.js'
import { startAndExecute } from '@/api/wf/wf.order.service.js'
import FormIndex from '@/views/modules/wf/form/index.vue'
export default {
  name: 'WfOrderAdd',
  components: {
    FormIndex
  },
  props: {
    id: {
      type: [String, Number],
      default: undefined
    }
  },
  data() {
    return {
      processList: [],
      instanceUrl: '',
      form: {
        processId: '',
        args: {}
      },
      rules: {
        processId: [
          { required: true, message: '流程定义ID不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    listProcess({
      pageNum: 1,
      pageSize: 100
    }).then(res => {
      if (res.code === 0) {
        this.processList = res.data.rows
      }
    })
  },
  methods: {
    submit() {
      return new Promise((resolve, reject) => {
        // 校验默认表单
        this.$refs.form.validate(valid => {
          if (valid) {
            // 校验自定义表单
            if (this.$refs[this.instanceUrl]) {
              this.$refs[this.instanceUrl].validate(mValid => {
                if (mValid) {
                  startAndExecute({
                    processId: this.form.processId,
                    args: this.$refs[this.instanceUrl].getFormData()
                  }).then(res => {
                    if (res.code === 0) {
                      this.$message({
                        message: res.msg || '操作成功',
                        type: 'success'
                      })
                    }
                    resolve(res)
                  }).catch(e => {
                    reject(e)
                  })
                } else {
                  reject(new Error('error'))
                }
              })
            }
          } else {
            reject(new Error('error'))
          }
        })
      })
    },
    resetFields() {
      this.$refs['form'].resetFields()
      this.$refs['form'].clearValidate()
    },
    handleChange(value) {
      this.processList.forEach(item => {
        if (value === item.id) {
          this.instanceUrl = item.instanceUrl
        }
      })
    }
  }
}
</script>
